<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>英语单词消消乐</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#6366f1',
                        secondary: '#ec4899',
                        accent1: '#10b981',
                        accent2: '#f59e0b',
                        accent3: '#ef4444',
                        dark: '#1f2937',
                        light: '#f9fafb'
                    },
                    fontFamily: {
                        game: ['Comic Sans MS', 'cursive', 'sans-serif']
                    }
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .word-card {
                @apply bg-white rounded-lg shadow-lg p-4 m-2 cursor-pointer transition-all duration-300 transform hover:scale-105 hover:shadow-xl;
            }
            .word-card-selected {
                @apply ring-4 ring-primary bg-blue-50;
            }
            .btn-primary {
                @apply bg-primary hover:bg-primary/90 text-white font-bold py-2 px-4 rounded transition-all duration-300 transform hover:scale-105 focus:outline-none focus:ring-2 focus:ring-primary focus:ring-opacity-50;
            }
            .btn-secondary {
                @apply bg-secondary hover:bg-secondary/90 text-white font-bold py-2 px-4 rounded transition-all duration-300 transform hover:scale-105 focus:outline-none focus:ring-2 focus:ring-secondary focus:ring-opacity-50;
            }
            .btn-danger {
                @apply bg-accent3 hover:bg-accent3/90 text-white font-bold py-2 px-4 rounded transition-all duration-300 transform hover:scale-105 focus:outline-none focus:ring-2 focus:ring-accent3 focus:ring-opacity-50;
            }
        }
    </style>
</head>
<body class="bg-gradient-to-br from-purple-100 to-blue-100 min-h-screen font-game">
    <div class="container mx-auto px-4 py-8">
        <!-- 游戏标题 -->
        <h1 class="text-[clamp(2rem,5vw,3.5rem)] font-bold text-center text-dark mb-8">
            <i class="fa fa-language text-primary"></i> 英语单词消消乐
        </h1>

        <!-- 操作和显示区域 -->
        <div class="bg-white rounded-xl shadow-xl p-6 mb-8">
            <div class="flex flex-col md:flex-row justify-between items-center gap-4">
                <!-- 操作按钮 -->
                <div class="flex flex-wrap gap-4 justify-center">
                    <button id="start-game" class="btn-primary">
                        <i class="fa fa-play mr-2"></i> 开始游戏
                    </button>
                    <button id="end-game" class="btn-danger" disabled>
                        <i class="fa fa-stop mr-2"></i> 结束游戏
                    </button>
                    <label for="file-upload" class="btn-secondary cursor-pointer">
                        <i class="fa fa-upload mr-2"></i> 选择文件
                    </label>
                    <input type="file" id="file-upload" accept=".xlsx,.xls" class="hidden">
                </div>
                <!-- 游戏信息 -->
                <div class="flex flex-col items-center">
                    <div id="game-status" class="text-lg font-semibold text-gray-600 mb-2">
                        游戏准备就绪
                    </div>
                    <div id="game-time" class="text-xl font-bold text-primary">
                        用时: 00:00
                    </div>
                </div>
            </div>
        </div>

        <!-- 游戏区域 -->
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <!-- 英文单词区域 -->
            <div id="english-words" class="bg-gradient-to-br from-accent1/10 to-accent1/20 rounded-xl shadow-lg p-6 min-h-[400px] overflow-y-auto">
                <h2 class="text-2xl font-bold text-center text-accent1 mb-4">
                    <i class="fa fa-book mr-2"></i> 英文单词
                </h2>
                <div id="english-words-container" class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-2 min-h-[300px]">
                    <div class="flex items-center justify-center h-full text-gray-500">
                        <i class="fa fa-info-circle mr-2"></i> 请上传单词表并开始游戏
                    </div>
                </div>
            </div>

            <!-- 中文单词区域 -->
            <div id="chinese-words" class="bg-gradient-to-br from-accent2/10 to-accent2/20 rounded-xl shadow-lg p-6 min-h-[400px] overflow-y-auto">
                <h2 class="text-2xl font-bold text-center text-accent2 mb-4">
                    <i class="fa fa-language mr-2"></i> 中文释义
                </h2>
                <div id="chinese-words-container" class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-2 min-h-[300px]">
                    <div class="flex items-center justify-center h-full text-gray-500">
                        <i class="fa fa-info-circle mr-2"></i> 请上传单词表并开始游戏
                    </div>
                </div>
            </div>
        </div>

        <!-- 游戏统计 -->
        <div class="mt-8 bg-white rounded-xl shadow-lg p-6">
            <h2 class="text-2xl font-bold text-center text-dark mb-4">
                <i class="fa fa-bar-chart mr-2"></i> 游戏统计
            </h2>
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4 text-center">
                <div class="bg-primary/10 p-4 rounded-lg">
                    <p class="text-gray-600">总单词数</p>
                    <p id="total-words" class="text-2xl font-bold text-primary">0</p>
                </div>
                <div class="bg-accent1/10 p-4 rounded-lg">
                    <p class="text-gray-600">已匹配</p>
                    <p id="matched-words" class="text-2xl font-bold text-accent1">0</p>
                </div>
                <div class="bg-accent3/10 p-4 rounded-lg">
                    <p class="text-gray-600">错误次数</p>
                    <p id="error-count" class="text-2xl font-bold text-accent3">0</p>
                </div>
            </div>
        </div>

        <!-- 错误提示模态框 -->
        <div id="error-modal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
            <div class="bg-white rounded-xl shadow-2xl p-8 max-w-md w-full mx-4 transform transition-all duration-300 scale-100">
                <div class="text-center">
                    <div class="text-accent3 text-4xl mb-4">
                        <i class="fa fa-times-circle"></i>
                    </div>
                    <h3 class="text-2xl font-bold text-dark mb-2">匹配错误</h3>
                    <p class="text-gray-600 mb-6">所选单词与释义不匹配，请重新选择。</p>
                    <button id="error-close" class="btn-primary">
                        确定
                    </button>
                </div>
            </div>
        </div>

        <!-- 游戏完成模态框 -->
        <div id="complete-modal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
            <div class="bg-white rounded-xl shadow-2xl p-8 max-w-md w-full mx-4 transform transition-all duration-300 scale-100">
                <div class="text-center">
                    <div class="text-accent1 text-4xl mb-4">
                        <i class="fa fa-trophy"></i>
                    </div>
                    <h3 class="text-2xl font-bold text-dark mb-2">恭喜完成！</h3>
                    <p class="text-gray-600 mb-2">总用时: <span id="final-time" class="font-bold text-primary">00:00</span></p>
                    <p class="text-gray-600 mb-6">错误次数: <span id="final-errors" class="font-bold text-accent3">0</span></p>
                    <button id="complete-close" class="btn-primary">
                        返回游戏
                    </button>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 游戏数据和状态
        const gameData = {
            words: [], // 单词数据
            selectedEnglish: null, // 选中的英文单词索引
            selectedChinese: null, // 选中的中文单词索引
            matched: new Set(), // 已匹配的单词对
            errors: 0, // 错误次数
            isPlaying: false, // 游戏状态
            startTime: null, // 游戏开始时间
            timer: null, // 计时器
            totalWords: 0 // 总单词数
        };

        // DOM元素
        const elements = {
            startGame: document.getElementById('start-game'),
            endGame: document.getElementById('end-game'),
            fileUpload: document.getElementById('file-upload'),
            gameStatus: document.getElementById('game-status'),
            gameTime: document.getElementById('game-time'),
            englishContainer: document.getElementById('english-words-container'),
            chineseContainer: document.getElementById('chinese-words-container'),
            totalWords: document.getElementById('total-words'),
            matchedWords: document.getElementById('matched-words'),
            errorCount: document.getElementById('error-count'),
            errorModal: document.getElementById('error-modal'),
            errorClose: document.getElementById('error-close'),
            completeModal: document.getElementById('complete-modal'),
            completeClose: document.getElementById('complete-close'),
            finalTime: document.getElementById('final-time'),
            finalErrors: document.getElementById('final-errors')
        };

        // 示例单词数据
        const sampleWords = [
            { english: 'apple', chinese: '苹果' },
            { english: 'banana', chinese: '香蕉' },
            { english: 'cat', chinese: '猫' },
            { english: 'dog', chinese: '狗' },
            { english: 'elephant', chinese: '大象' },
            { english: 'fish', chinese: '鱼' },
            { english: 'guitar', chinese: '吉他' },
            { english: 'hat', chinese: '帽子' },
            { english: 'ice', chinese: '冰' },
            { english: 'juice', chinese: '果汁' }
        ];

        // 初始化
        function init() {
            // 加载示例数据
            loadWords(sampleWords);
            
            // 添加事件监听器
            elements.startGame.addEventListener('click', startGame);
            elements.endGame.addEventListener('click', endGame);
            elements.fileUpload.addEventListener('change', handleFileUpload);
            elements.errorClose.addEventListener('click', () => elements.errorModal.classList.add('hidden'));
            elements.completeClose.addEventListener('click', () => elements.completeModal.classList.add('hidden'));
        }

        // 加载单词数据
        function loadWords(words) {
            gameData.words = [...words];
            gameData.totalWords = words.length;
            elements.totalWords.textContent = gameData.totalWords;
            elements.matchedWords.textContent = 0;
            elements.errorCount.textContent = 0;
            
            // 重置游戏状态
            gameData.matched.clear();
            gameData.errors = 0;
            gameData.selectedEnglish = null;
            gameData.selectedChinese = null;
            
            if (!gameData.isPlaying) {
                renderWords();
            }
        }

        // 渲染单词
        function renderWords() {
            // 清空容器
            elements.englishContainer.innerHTML = '';
            elements.chineseContainer.innerHTML = '';
            
            if (gameData.words.length === 0) {
                const emptyMessage = document.createElement('div');
                emptyMessage.className = 'flex items-center justify-center h-full text-gray-500';
                emptyMessage.innerHTML = '<i class="fa fa-info-circle mr-2"></i> 请上传单词表';
                elements.englishContainer.appendChild(emptyMessage);
                elements.chineseContainer.appendChild(emptyMessage.cloneNode(true));
                return;
            }
            
            // 打乱中文单词顺序
            const shuffledChinese = [...gameData.words].sort(() => Math.random() - 0.5);
            
            // 渲染英文单词
            gameData.words.forEach((word, index) => {
                if (gameData.matched.has(index)) return;
                
                const card = createWordCard(word.english, index, 'english');
                elements.englishContainer.appendChild(card);
            });
            
            // 渲染中文单词
            shuffledChinese.forEach((word, index) => {
                const originalIndex = gameData.words.findIndex(w => w.chinese === word.chinese);
                if (gameData.matched.has(originalIndex)) return;
                
                const card = createWordCard(word.chinese, originalIndex, 'chinese');
                elements.chineseContainer.appendChild(card);
            });
            
            // 如果没有单词显示提示
            if (elements.englishContainer.children.length === 0) {
                const emptyMessage = document.createElement('div');
                emptyMessage.className = 'flex items-center justify-center h-full text-gray-500';
                emptyMessage.innerHTML = '<i class="fa fa-check-circle mr-2"></i> 所有单词已匹配完成！';
                elements.englishContainer.appendChild(emptyMessage);
                elements.chineseContainer.appendChild(emptyMessage.cloneNode(true));
            }
        }

        // 创建单词卡片
        function createWordCard(text, index, type) {
            const card = document.createElement('div');
            card.className = 'word-card';
            card.dataset.index = index;
            card.dataset.type = type;
            card.innerHTML = `<span class="text-lg font-semibold">${text}</span>`;
            
            // 添加点击事件
            card.addEventListener('click', () => handleWordClick(card));
            
            return card;
        }

        // 处理单词点击
        function handleWordClick(card) {
            if (!gameData.isPlaying) return;
            
            const index = parseInt(card.dataset.index);
            const type = card.dataset.type;
            
            // 如果已经匹配，则忽略
            if (gameData.matched.has(index)) return;
            
            // 清除之前的选中状态
            clearSelection();
            
            // 设置新的选中状态
            if (type === 'english') {
                gameData.selectedEnglish = index;
            } else {
                gameData.selectedChinese = index;
            }
            
            card.classList.add('word-card-selected');
            
            // 检查是否完成了一对选择
            if (gameData.selectedEnglish !== null && gameData.selectedChinese !== null) {
                checkMatch();
            }
        }

        // 清除选中状态
        function clearSelection() {
            const selectedCards = document.querySelectorAll('.word-card-selected');
            selectedCards.forEach(card => card.classList.remove('word-card-selected'));
        }

        // 检查匹配
        function checkMatch() {
            const { selectedEnglish, selectedChinese } = gameData;
            
            // 延迟处理，让用户看到选择效果
            setTimeout(() => {
                if (selectedEnglish === selectedChinese) {
                    // 匹配成功
                    gameData.matched.add(selectedEnglish);
                    elements.matchedWords.textContent = gameData.matched.size;
                    
                    // 检查游戏是否完成
                    if (gameData.matched.size === gameData.totalWords) {
                        gameComplete();
                    }
                } else {
                    // 匹配失败
                    gameData.errors++;
                    elements.errorCount.textContent = gameData.errors;
                    
                    // 显示错误提示
                    elements.errorModal.classList.remove('hidden');
                    // 添加动画效果
                    const modalContent = elements.errorModal.querySelector('div');
                    modalContent.classList.add('scale-95');
                    setTimeout(() => modalContent.classList.remove('scale-95'), 300);
                }
                
                // 重置选择
                gameData.selectedEnglish = null;
                gameData.selectedChinese = null;
                
                // 重新渲染单词
                renderWords();
            }, 300);
        }

        // 开始游戏
        function startGame() {
            if (gameData.words.length === 0) {
                alert('请先上传单词表或使用示例数据！');
                return;
            }
            
            // 重置游戏状态
            gameData.matched.clear();
            gameData.errors = 0;
            gameData.selectedEnglish = null;
            gameData.selectedChinese = null;
            gameData.isPlaying = true;
            gameData.startTime = new Date();
            
            // 更新UI
            elements.gameStatus.textContent = '游戏进行中...';
            elements.startGame.disabled = true;
            elements.endGame.disabled = false;
            elements.fileUpload.disabled = true;
            elements.matchedWords.textContent = 0;
            elements.errorCount.textContent = 0;
            
            // 打乱单词顺序
            gameData.words.sort(() => Math.random() - 0.5);
            
            // 开始计时
            startTimer();
            
            // 渲染单词
            renderWords();
        }

        // 结束游戏
        function endGame() {
            gameData.isPlaying = false;
            clearInterval(gameData.timer);
            
            // 更新UI
            elements.gameStatus.textContent = '游戏已结束';
            elements.startGame.disabled = false;
            elements.endGame.disabled = true;
            elements.fileUpload.disabled = false;
            
            // 重置选中状态
            gameData.selectedEnglish = null;
            gameData.selectedChinese = null;
            
            // 重新渲染单词
            renderWords();
        }

        // 开始计时
        function startTimer() {
            clearInterval(gameData.timer);
            
            gameData.timer = setInterval(() => {
                const now = new Date();
                const elapsed = Math.floor((now - gameData.startTime) / 1000);
                const minutes = Math.floor(elapsed / 60).toString().padStart(2, '0');
                const seconds = (elapsed % 60).toString().padStart(2, '0');
                
                elements.gameTime.textContent = `用时: ${minutes}:${seconds}`;
            }, 1000);
        }

        // 游戏完成
        function gameComplete() {
            gameData.isPlaying = false;
            clearInterval(gameData.timer);
            
            // 更新UI
            elements.gameStatus.textContent = '游戏完成！';
            elements.startGame.disabled = false;
            elements.endGame.disabled = true;
            elements.fileUpload.disabled = false;
            
            // 显示完成模态框
            elements.finalTime.textContent = elements.gameTime.textContent.replace('用时: ', '');
            elements.finalErrors.textContent = gameData.errors;
            elements.completeModal.classList.remove('hidden');
            
            // 添加动画效果
            const modalContent = elements.completeModal.querySelector('div');
            modalContent.classList.add('scale-95');
            setTimeout(() => modalContent.classList.remove('scale-95'), 300);
        }

        // 处理文件上传
        function handleFileUpload(event) {
            const file = event.target.files[0];
            if (!file) return;
            
            const reader = new FileReader();
            reader.onload = function(e) {
                try {
                    const data = new Uint8Array(e.target.result);
                    const workbook = XLSX.read(data, { type: 'array' });
                    const sheetName = workbook.SheetNames[0];
                    const worksheet = workbook.Sheets[sheetName];
                    const jsonData = XLSX.utils.sheet_to_json(worksheet);
                    
                    // 处理数据，假设第一列是英文，第二列是中文
                    const words = [];
                    jsonData.forEach(row => {
                        const keys = Object.keys(row);
                        if (keys.length >= 2) {
                            words.push({
                                english: row[keys[0]].toString().trim(),
                                chinese: row[keys[1]].toString().trim()
                            });
                        }
                    });
                    
                    if (words.length > 0) {
                        loadWords(words);
                        elements.gameStatus.textContent = '单词表已加载，点击开始游戏';
                        alert(`成功加载 ${words.length} 个单词！`);
                    } else {
                        alert('未找到有效的单词数据，请检查Excel文件格式。');
                    }
                } catch (error) {
                    alert('文件解析错误: ' + error.message);
                }
            };
            reader.readAsArrayBuffer(file);
        }

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', init);
    </script>
</body>
</html>